package test;

import java.io.IOException;  
import java.nio.ByteBuffer;  
import java.nio.channels.SelectionKey;  
import java.nio.channels.ServerSocketChannel;  
import java.nio.channels.SocketChannel;  
import java.nio.charset.Charset;  
/** 
 * 服务器端接口实现类 
 * @author Administrator 
 * 
 */  
public class ProtocolImplement implements Protocol{  
    private int buffersize;  
      
    public ProtocolImplement(int buffersize){  
        this.buffersize = buffersize;  
    }  
      
    public void handleAccept(SelectionKey key)throws IOException{  
        SocketChannel clientchannel = ((ServerSocketChannel)key.channel()).accept();  
        clientchannel.configureBlocking(false);  
        clientchannel.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(buffersize));  
    }  
      
    public void handleRead(SelectionKey key)throws IOException{  
        SocketChannel clientchannel = (SocketChannel)key.channel();  
        //得到并清空缓冲区  
        ByteBuffer buffer  = (ByteBuffer)key.attachment();  
        buffer.clear();  
        //读取信息获得读取的字节数  
        long bytesRead = clientchannel.read(buffer);  
          
        if(bytesRead == -1){  
            //没有读取到内容  
            clientchannel.close();  
        }else{  
            //将缓冲区准备为数据传出状态  
            buffer.flip();  
            String receivedString = Charset.forName("UTF-16").newDecoder().decode(buffer).toString();  
            //打印  
            System.out.println("客户端"+clientchannel.socket().getRemoteSocketAddress()+":"+receivedString);  
            //为下一次读取或写入做准备  
            key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);  
        }  
    }  
      
    public void handleWrite(SelectionKey key)throws IOException{  
        SocketChannel clientchannel = (SocketChannel)key.channel();  
        ByteBuffer writeBuffer = ByteBuffer.wrap(Server.msg.getBytes("UTF-16"));  
        clientchannel.write(writeBuffer);  
        key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);  
    }  
  
  
} 